<template>
    <div 
         class="toast-container">
        <cv-toast-notification  
        :kind="kind"
        :title="title"
        :sub-title="subTitle"
        :caption="caption"
        @close="dismiss"
        :low-contrast=lowContrast
        class="cv-toast"
        ></cv-toast-notification>

  <!-- <component
    :is="tag"
    v-bind="urlTarget"
    class="vt-notification"
    :style="draggableStyles"
    :class="notificationClass"
    @click="dismiss()"
    @mouseenter="isHovered = true"
    @mouseleave="isHovered = false"
    @touchstart="isHovered = true"
    @touchend="isHovered = false"
  > -->
    <!-- <ProgressBar
      v-if="isNotification && status.canTimeout"
      :can-pause="status.canPause"
      :duration="status.duration"
      :is-hovered="isHovered"
      :hide-progressbar="status.hideProgressbar"
      :id="status.id"
      :ref="'progress-' + status.id"
      @vtFinished="closeNotification"
    /> -->
    </div>
    <!-- <div class="vt-content">
      <h2 class="vt-title" v-if="status.title" v-text="status.title" />
      <p class="vt-paragraph" v-html="status.body" />
    </div> -->
    <!-- <Icon
      v-if="status.iconEnabled"
      :mode="status.mode"
      :type="status.type"
      :icon="status.icon"
      :base-icon-class="baseIconClass"
    /> -->
    <!-- <div class="vt-buttons" v-if="status.mode === 'prompt'">
      <button
        v-for="(value, answerProperty, index) in status.answers"
        :key="index"
        @click="respond(value)"
        v-text="answerProperty"
      />
    </div> -->
  <!-- </component> -->
</template>

<script>
// import ProgressBar from "./ProgressBar";
// import Icon from "./Icon.vue";
// import draggable from "./draggable.js";
export default {
  name: "CvToastContainer",
  // components: { ProgressBar,  },
  props: {
    status: { type: Object },
    baseIconClass: { type: String, default: "" }
  },
  // mixins: [draggable],
  data() {
    return {
      isHovered: false,
      // "title": "Changes saved from landing page",
      'title': '',
      'kind': 'error',
      // "subTitle": "a subtitle",
      "subTitle": null,
      // "caption": "Time stamp [00:00:00]",
      "caption": null,
      lowContrast: true,

      progress: 0,
      progressId: null,
      timerId: null,
      timerStartedAt: null,
      timerPausedAt: null,
      timerFinishesAt: null,
      // duration: 3000,
    };
  },
  // beforeMount() {
  //   console.log('kind=' + this.kind);
  //   this.timerFinishesAt = new Date(this.duration + Date.now());
  // },
  mounted() {
    console.log('mounted');
    console.log(this.status);
    this.title = this.status.title;
    this.kind = this.status.type;
    console.log(this.status.id);

    console.log('kind=' + this.kind);
    let duration = 3000;
    if (this.kind == 'error') {
      duration = 10000;
    }
    this.timerFinishesAt = new Date(duration + Date.now());


    this.$root.$emit("vtStarted", { id: this.status.id });
    // start of the timer (a constant)
    this.timerStartedAt = new Date();
    // initial time to calculate with on the first start
    this.timerPausedAt = new Date();
    this.timerStart();

    //if there is an initial notification
    if (this.status.mode === "loader") {
      this.$root.$once("vtLoadStop", payload => {
        //if all loaders should stop or only this
        if (payload.id) {
          if (payload.id === this.status.id) {
            this.closeNotification();
          }
        } else {
          this.closeNotification();
        }
      });
    }
  },
  computed: {
    tag() {
      if (!this.status.url || this.status.url.length === 0) {
        return "div";
      }
      // if (this.hasRouter && this.status.url.length > 0) { // todo = notification doesn't show if has router
      //   return "router-link";
      // }
      return "a";
    },
    urlTarget() {
      if (!this.status.url || this.status.url.length === 0) {
        return {};
      }
      // if (this.hasRouter) {
      //   return { to: this.status.url };
      // }
      return { href: this.status.url };
    },
    // hasRouter() {
    //   return !!this.$root.$options._base._installedPlugins.find(entry => {
    //     return entry.hasOwnProperty("name") && entry.name === "VueRouter";
    //   });
    // }
    notificationClass() {
      let obj = {};
      if (this.status.url && this.status.url.length > 0) {
        obj["vt-cursor-pointer"] = true;
      } else if (this.status.mode === "loader") {
        obj["vt-cursor-wait"] = true;
      }
      obj["vt-theme-" + this.status.theme] = true;
      return obj;
    },
    isNotification() {
      return ["prompt", "loader"].indexOf(this.status.mode) === -1;
    }
  },
  methods: {
    timerStart() {
      // if (this.canPause) {
      if (true) {
        this.timerStartedAt = new Date(
          this.timerStartedAt.getTime() +
            (Date.now() - this.timerPausedAt.getTime())
        );

        // new future date = future date + elapsed time since pausing
        this.timerFinishesAt = new Date(
          this.timerFinishesAt.getTime() +
            (Date.now() - this.timerPausedAt.getTime())
        );

        // if (!this.timerId && this.progress > 0) {
        //   this.$root.$emit("vtResumed", { id: this.id });
        // }

        // set new timeout
        console.log('setting timeout for:');
        console.log(this.timerFinishesAt.getTime() - Date.now());
        // this.timerId = window.setTimeout(
        //   () => this.$emit("vtFinished"),
        //   this.timerFinishesAt.getTime() - Date.now()
        // );
        this.timerId = window.setTimeout(
          () => {console.log('finished!'); this.closeNotification();},
          this.timerFinishesAt.getTime() - Date.now()
        );        
        // this.timerId = window.setTimeout(
        //   () => {console.log('finished!'); this.closeNotification();},
        //   3000
        // );        
        // animation start
        // this.progressId = requestAnimationFrame(this.progressBar);
      }
    },    
    closeNotification() {
      const progress = Math.ceil(
        this.$refs["progress-" + this.status.id]
          ? this.$refs["progress-" + this.status.id].progress
          : undefined
      );

      // if notification manually dismissed before the the timeout or in case if it cannot timeout AND isn't prompt or loader
      if ((isNaN(progress) || progress < 100) && this.isNotification) {
        this.$root.$emit("vtDismissed", { id: this.status.id });
        this.status.callback ? this.status.callback() : null;
      }
      // if the notification has finished displaying
      if (progress >= 100 && this.isNotification) {
        this.$root.$emit("vtFinished", { id: this.status.id });
        this.status.callback ? this.status.callback() : null;
      }
    },
    dismiss() {
      console.log('about to dismiss...');
      if (this.isNotification && !this.hasMoved) {
        this.closeNotification();
      }
    },
    respond(response) {
      this.closeNotification();
      this.$root.$emit("vtPromptResponse", {
        id: this.status.id,
        response: response
      });
    }
  }
};
</script>

<style scoped>

.cv-toast {
  margin-bottom: auto;
  margin-left: auto;
  margin-right: auto;
}


</style>